import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:restart_app/restart_app.dart';
import 'package:shorebird_code_push/shorebird_code_push.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';

class UpdatePatchUtil {
  final ShorebirdCodePush _shorebirdCodePush = ShorebirdCodePush();

  bool _isUpdateAvailable = false;

  bool isDownloadSuccess = false;

  static UpdatePatchUtil? _instance;

  UpdatePatchUtil._internal();

  factory UpdatePatchUtil() {
    _instance ??= UpdatePatchUtil._internal();

    return _instance!;
  }

  Future<void> updatePatch() async {
    _isUpdateAvailable =
        await _shorebirdCodePush.isNewPatchAvailableForDownload();
    Log.d('_isUpdateAvailable==' + _isUpdateAvailable.toString());
    if (_isUpdateAvailable) {
      await goToUpdate();
    }
  }

  ///去更新
  Future<void> goToUpdate() async {
    await Future.wait([
      _shorebirdCodePush.downloadUpdateIfAvailable(),
      // Add an artificial delay so the banner has enough time to animate in.
      Future<void>.delayed(const Duration(milliseconds: 250)),
    ]);
    Log.d('bool: patch 更新成功');
    isDownloadSuccess = await _shorebirdCodePush.isNewPatchReadyToInstall();
  }

  showRestartDialog(BuildContext context) async {
    var currentPatchNumber = await _shorebirdCodePush.currentPatchNumber();
    var nextPatchNumber = await _shorebirdCodePush.nextPatchNumber();

    var text =
        'isDownloadSuccess:$isDownloadSuccess;\n_isUpdateAvailable:$_isUpdateAvailable;\n '
        'currentPatchNumber:$currentPatchNumber,\n nextPatchNumber: $nextPatchNumber  ';

    if (true) {
      return showDialog(
          barrierDismissible: true,
          context: context,
          builder: (BuildContext context) {
            return PatchUpdateDialog(
              shorebird: _shorebirdCodePush,
              tip: text,
            );
          });
    }
  }
}

class PatchUpdateDialog extends Dialog {
  final ShorebirdCodePush shorebird;
  final String? tip;
  const PatchUpdateDialog({super.key, required this.shorebird, this.tip});
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 300.w,
            height: 390.h,
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(16)),
            child: Stack(
              children: <Widget>[
                SizedBox(
                  // width: double.infinity,
                  child: Column(
                    // mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Gaps.vGap20,
                      ClipOval(
                        child: Image.asset(
                          ImageAssets.iconPatchUpdate,
                          fit: BoxFit.fill,
                          width: 144.w,
                          height: 144.w,
                        ),
                      ),
                      Text(ResKey.upgradeTip.tr,
                          style: ytTextStyle(
                              fontSize: 18.sp,
                              color: Colors.black,
                              fontWeight: FontWeight.bold,
                              height: 2.5.h)),
                      Container(
                          margin: EdgeInsets.only(left: 48.w, right: 42.w),
                          child: Text(tip ?? ResKey.upgradeRestarTip.tr,
                              textAlign: TextAlign.center,
                              style: ytTextStyle(
                                fontSize: 14.sp,
                                color: Colour.otherTextColor,
                                height: 1.5.h,
                              ))),
                      Spacer(),
                      BrnSmallMainButton(
                        title: ResKey.upgradeRestarNow.tr,
                        width: 260.w,
                        fontWeight: FontWeight.normal,
                        themeData: BrnButtonConfig(smallButtonHeight: 48.h),
                        onTap: () {
                          navigator?.pop();
                          restartApp();
                        },
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              margin: EdgeInsets.only(top: 24.h),
              child: Image.asset(
                ImageAssets.appUpdateClose,
                fit: BoxFit.fill,
                width: 34,
                height: 34,
              ),
            ),
          )
        ],
      ),
    );
  }

  // 重启app
  restartApp() {
    Restart.restartApp();
  }
}
